package com.example.bookkeepingelf.business.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.example.bookkeepingelf.R;
import com.example.bookkeepingelf.base.utils.AsyncUtils;
import com.example.bookkeepingelf.base.utils.ToastUtils;
import com.example.bookkeepingelf.business.adapter.AccountBookManageListContentListViewAdapter;
import com.example.bookkeepingelf.business.constant.AccountBookConstant;
import com.example.bookkeepingelf.business.database.AppDatabase;
import com.example.bookkeepingelf.business.database.dao.AccountBookDao;
import com.example.bookkeepingelf.business.database.entity.AccountBook;
import com.example.bookkeepingelf.business.listener.MyOnClickListener;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollectionUtil;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AccountBookManageListContentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AccountBookManageListContentFragment extends Fragment implements MyOnClickListener<AccountBook> {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ListView accountBookListView;

    private AppDatabase appDatabase;

    private List<AccountBook> accountBooks;

    private AccountBookManageListContentListViewAdapter arrayAdapter;

    private View view;

    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    if (CollectionUtil.isEmpty(accountBooks)) {
                        return;
                    }
                    if (arrayAdapter == null) {
                        arrayAdapter = new AccountBookManageListContentListViewAdapter(view.getContext(),AccountBookManageListContentFragment.this, R.layout.account_book_manage_list_content_item, accountBooks);
                        accountBookListView.setAdapter(arrayAdapter);
                    }else {
                        arrayAdapter.clear(); // 清空现有数据
                        arrayAdapter.addAll(accountBooks); // 添加新的数据
                        arrayAdapter.notifyDataSetChanged();
                    }
                    break;
            }

        }
    };



    public AccountBookManageListContentFragment(AppDatabase appDatabase) {
        this.appDatabase = appDatabase;
    }


    public AccountBookManageListContentFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AccountBookManageListContentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AccountBookManageListContentFragment newInstance(String param1, String param2) {
        AccountBookManageListContentFragment fragment = new AccountBookManageListContentFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        this.view = inflater.inflate(R.layout.fragment_account_book_manage_list_content, container, false);

        this.accountBookListView = view.findViewById(R.id.list_view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        this.refreshDate();
    }

    private void refreshDate() {
        AccountBookDao accountBookDao = this.appDatabase.accountBookDao();
        AsyncUtils.runSingle(() -> {
            this.accountBooks = accountBookDao.getAllOrderByUpdateTime();
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }, true);
    }

    @Override
    public void onMyClickChange(AccountBook accountBook) {
        if (Objects.isNull(accountBook)) {
            return;
        }
        if (accountBook.getMain()) {
            return;
        }
        accountBook.setMain(true);
        accountBook.setUpdateTime(new Date());
        //查询旧主账本
        AccountBookDao accountBookDao = this.appDatabase.accountBookDao();
        AsyncUtils.runSingle(() -> {
            AccountBook oldMainAccountBook = accountBookDao.getMainAccountBook();
            if (Objects.nonNull(oldMainAccountBook)) {
                oldMainAccountBook.setMain(false);
                accountBookDao.update(oldMainAccountBook);
            }
            accountBookDao.update(accountBook);

            this.refreshDate();
        }, true);
    }

    @Override
    public void onMyClickDelete(AccountBook accountBook) {
        //删除账本
        if (Objects.isNull(accountBook)) {
            return;
        }
        if (accountBook.getMain()) {
            ToastUtils.showCustomToast(view.getContext(), view, "无法删除主账本，请切换后重试");
            return;
        }
        AsyncUtils.runSingle(() -> {
            this.appDatabase.accountBookDao().delete(accountBook);
            refreshDate();
        }, true);
    }

    @Override
    public void onMyClickUpdate(AccountBook accountBook) {
        //编辑 跳转活动
        if (Objects.isNull(accountBook)) {
            return;
        }
        //跳转到添加账本页面
        Intent intent = new Intent(getContext(), AddAccountBookActivity.class);
        String jsonString = JSONObject.toJSONString(accountBook);
        intent.putExtra(AccountBookConstant.IS_UPDATE, true);
        intent.putExtra(AccountBookConstant.UPDATE_ACCOUNT_BOOK, jsonString);
        startActivity(intent);
    }
}